import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moduleName from '../../../modules/Ueditor';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import Editor from '@/utils/Editor';
import { routerRedux } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Form,
  Input,
  Button,
  Select,
  Modal,
  message,
  Tabs,
} from 'antd';
import styles from './index.less';
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const TabPane = Tabs.TabPane;
@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['antistopReply/fetch'],
}))
class editUeditor extends Component {
  constructor() {
    super();
    this.state = {
      list: [],
      total: '',
      showModelA: false,
      dataSource: [],
      name: '',
      data: {},
      dictId: '',
      content: '',
      areatext: '',
      key: '1',
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    if (this.props.location.params === undefined) {
      dispatch(
        routerRedux.push({
          // pathname: '/knowledge/antistopReply',
          pathname: "/basic/antistopReply",
        })
      );
    } else {
      const { dictName, dictId, answer, id } = JSON.parse(this.props.location.query.id);
      this.setState({
        name: dictName,
        dictId,
        content: answer,
        id
      });
      this.antistoplist();
    }
  }

  antistoplist = () => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'antistopReply/fetche',
        payload: { robotId: currentUser.robotId },
        callback: res => {
          let temp = res;
          // temp.map((item, index) => item['key'] = index)
          this.setState({
            dataSource: temp,
          });
        },
      });
    });
  };

  handleDeletes = () => {
    this.setState({ showModelA: true }, () => {
      this.antistoplist();
    });
  };

  handleChange = value => {
    this.setState({
      dictId: value[0],
      name: value[1],
    });
  };

  knowBase = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'antistopReply/fetchf',
      payload: { dictId: this.state.dictId },
      callback: res => {
        if (!res.enable) {
          this.setState({ showModelA: false, showButton: false });
          message['success']('词典认证成功');
        } else {
          message['error']('该词典已被使用，请选择其它词典！');
        }
      },
    });
  };

  jumpDictionaryPage = () => {
    const w = window.open('about:blank');
    w.location.href = '/knowledgeDesign/customDictionary';
    this.setState({ showModelA: false });
  };

  // eslint-disable-next-line react/sort-comp
  save() {
    this.addapi(this.ueditor.getUeditorContent());
  }

  saveTextArea = () => {
    const { value } = this.state;
    this.addapi(value);
  };

  textAreaid = e => {
    this.setState({ value: e.target.value });
  };

  addapi = val => {
    // fetchc'
    const { dictId } = this.state;
    if (dictId) {
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'antistopReply/fetchb',
          payload: { dictId: this.state.dictId, newAnswer: val, _id: this.state.id },
          callback: res => {
            if (res.status) {
              message['success'](`${res.msg}`);
              setTimeout(() => {
                dispatch(
                  routerRedux.push({
                    // pathname: '/knowledge/antistopReply',
                    pathname: "/basic/antistopReply",
                  })
                );
              }, 1000);
            }
          },
        });
      });
    } else {
      message['error']('词典名称不能为空');
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: { xs: 24, sm: 4, md: 3, },
      wrapperCol: { xs: 24, sm: 20, md: 21, },
    };

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div className={styles.backgroundp}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10, color: '#4B5475', fontWeight: 600 }} xs={24}>
                <div className={styles.title}>
                  <FormattedMessage id="app.antistopReply.editAntistopRevert" />
                </div>
              </Col>
            </Row>
            <Card style={{ zIndex: 1 }} bordered={false}>
              <Form layout="horizontal">
                <FormItem label="关键词实体" {...FormItemLayont}>
                  <div>
                    <span className={styles.configuration}>{this.state.name}</span>{' '}
                    <span className={styles.buttong2} onClick={this.handleDeletes}>
                      <span>
                        <Icon type="edit" style={{ marginRight: 5 }} />
                      </span>
                      <span>
                        <FormattedMessage id="app.antistopReply.change" />
                      </span>
                    </span>
                  </div>
                </FormItem>
                <FormItem label="关键词回复" {...FormItemLayont}>
                  <Tabs defaultActiveKey="1" style={{ width: 650 }}>
                    <TabPane tab="编辑富文本" key="1">
                      <div style={{ lineHeight: '20px', width: 650 }}>
                        <Editor content={this.state.content} name="content" id="content" height="300" width="500" ref={r => (this.ueditor = r)} />
                        <div className="zdyButtonA">
                          <Button type="primary" style={{ marginTop: 10 }} onClick={() => this.save()}>保存</Button>
                        </div>
                      </div>
                    </TabPane>
                    <TabPane tab="编辑文本" key="2">
                      <TextArea rows={4} style={{ height: 300 }} defaultValue={this.state.areatext} onChange={this.textAreaid} />
                      <div className="zdyButtonA">
                        <Button type="primary" style={{ marginTop: 10 }} onClick={() => this.saveTextArea()}>保存</Button>
                      </div>
                    </TabPane>
                  </Tabs>
                </FormItem>
              </Form>
            </Card>

            <Modal
              className="modelZdy"
              width={490}
              footer={null}
              title="添加/更换实体"
              visible={this.state.showModelA}
              okText={<FormattedMessage id="app.customDictionary.save" />}
              cancelText={<FormattedMessage id="app.customDictionary.cancel" />}
              onCancel={() => {
                this.setState({ showModelA: false });
              }}
              onOk={this.businessWayA} // 确定方法开出去
            >
              <Form layout="inline">
                <FormItem onSubmit={this.coreWordOne}>
                  <Select showSearch={true} defaultValue={this.state.name} style={{ width: 220 }} onChange={this.handleChange}>
                    {this.state.dataSource.map((item, index) => {
                      return <Option value={[item._id, item.name]}>{item.name}</Option>;
                    })}
                  </Select>
                </FormItem>
                <FormItem>
                  <Button onClick={this.knowBase}>选择</Button>
                </FormItem>
                <FormItem>
                  <Button onClick={this.jumpDictionaryPage} type="primary">选择实体</Button>
                </FormItem>
              </Form>
              <div style={{ height: 20 }} />
            </Modal>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(editUeditor));
